<template>
  <div class="health-atlas-page">
    <!-- 头部导航 -->
    <AppHeader
        :user-info="userInfo"
        @go-to-profile="handleGoToProfile"
        @quick-appointment="handleQuickAppointment"
    />

    <!-- 主体布局 -->
    <div class="main-layout">
      <!-- 侧边栏 -->
      <aside class="sidebar-wrapper">
        <HealthAtlasSidebar
            :is-visible="sidebarVisible"
            :mode="'embedded'"
            :menu-items="sidebarMenuItems"
            @navigate="handleNavigation"
            @close="closeSidebar"
        />
      </aside>

      <!-- 主内容区 -->
      <main class="content-wrapper">
        <router-view v-if="$route.path !== '/patient'"></router-view>
        <template v-else>
        <PatientMainContent
            :patient-info="patientInfo"
            :active-tab="activeTab"
            :diagnosis-data="diagnosisData"
            @tab-change="handleTabChange"
            @data-update="handleDataUpdate"
            v-if="!activeComponent && !$route.meta.hideDefault"
        />

        <!-- 动态组件 -->
        <component
            v-else
            :is="activeComponent"
            :patient-info="patientInfo"
            @back="activeComponent = null"
        />
      </template>
      </main>
    </div>
    <Footer/>
    <!-- 全局模态框 -->
    <Teleport to="body">
      <ConfirmDialog
          v-model:visible="confirmDialog.visible"
          :title="confirmDialog.title"
          :message="confirmDialog.message"
          :type="confirmDialog.type"
          @confirm="confirmDialog.onConfirm"
          @cancel="confirmDialog.onCancel"
      />
    </Teleport>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, provide, defineAsyncComponent} from 'vue'
import { useRouter } from 'vue-router'
import AppHeader from '../components/PatientHeader.vue'
import HealthAtlasSidebar from '../components/Sidebar.vue'
import PatientMainContent from '../components/PatientMainContent.vue'
import ConfirmDialog from '../components/ConfirmDialog.vue'
import { useHealthAtlasStore } from '../stores/store' // 导入 useHealthAtlasStore
import { ElMessage } from 'element-plus'
import Footer from "../components/Footer.vue";


// Composable
const router = useRouter()
const store = useHealthAtlasStore() // 正确使用 useHealthAtlasStore


// 响应式数据
const sidebarVisible = ref(true)
const activeTab = ref('western')
const activeComponent = ref(null)

// 动态组件映射
const componentMap = {
  'today-appointments': defineAsyncComponent(() => import('../components/panels/TodayAppointments.vue')),
  'quick-consult': defineAsyncComponent(() => import('../components/panels/QuickConsult.vue')),
  'patient-management': defineAsyncComponent(() => import('../components/panels/PatientManagement.vue')),
  'western-medicine': defineAsyncComponent(() => import('../components/panels/WesternDiagnosis.vue')),
  'tcm-syndrome': defineAsyncComponent(() => import('../components/panels/TcmDifferentiation.vue')),
  'health-assessment': defineAsyncComponent(() => import('../components/panels/HealthAssessment.vue')),
  'western-medication': defineAsyncComponent(() => import('../components/panels/WesternMedication.vue')),
  'tcm-medication': defineAsyncComponent(() => import('../components/panels/TcmMedication.vue')),
  'vitals': defineAsyncComponent(() => import('../components/panels/VitalSigns.vue')),
  'reports': defineAsyncComponent(() => import('../components/panels/MedicalReports.vue')),
  'medical-records': defineAsyncComponent(() => import('../components/panels/MedicalRecords.vue')),
  'first-aid': defineAsyncComponent(() => import('../components/panels/FirstAidGuide.vue')),
  'find-hospital': defineAsyncComponent(() => import('../components/panels/HospitalFinder.vue')),
  'system-settings': defineAsyncComponent(() => import('../components/Settings.vue')),
}

// 侧边栏菜单项，用于 HealthAtlasSidebar 组件
const sidebarMenuItems = ref([
  {
    id: 'today-appointments',
    text: '今日预约',
    icon: 'Calendar', // 使用 Element Plus 图标
    badge:true ,//支持未读标记
    route: 'today-appointments',
    component: 'today-appointments'
  },
  {
    id:'quick-consult',
    text: '急速问诊',
    icon: 'Promotion',
    route: '/telemedicine',
    hot:true,
    component: 'quick-consult'
  },
  {
    id: 'patient-management',
    text: '个人信息',
    icon: 'UserFilled', // 使用 Element Plus 图标
    route: 'patient-management',
    component: 'patient-management'
  },
  {
    id: 'intelligent-diagnosis',
    text: '专业问诊',
    icon: 'Monitor', // 使用 Element Plus 图标
    children: [
      { id: 'western-diagnosis',
        text: '西医诊断',
        icon: 'FirstAidKit',
        route:'western-diagnosis',
        component: 'western-diagnosis'
      },
      { id: 'tcm-differentiation',
        text: '中医辨证',
        icon: 'Document',
        route: 'tcm-differentiation',
        component: 'tcm-differentiation'
      }
    ]
  },
  {
    id: 'health-assessment',
    text: '健康评估',
    icon: 'FirstAidKit',
    route: 'health-assessment',
    component: 'health-assessment'
  },
  {
    id: 'my-medication',
    text: '我的用药',
    icon: 'Box',
    children: [
      {
        id:'western-medication',
        text: '西药用药',
        icon: 'PieChart',
        badge: true, //显示待服药提醒
        route: 'western-medication',
        component: 'western-medication'
      },
      {
        id:'tcm-medication',
        text: '中药用药',
        icon: 'Leaf',
        badge: true,
        route: 'tcm-medication',
        component: 'tcm-medication'
      },
      
    ]
  },
  {
    id: 'health-data',
    text: '健康档案',
    icon: 'FolderOpened',
    children: [
      {
        id:'vitals',
        text: '体征记录',
        icon: 'DataLine',
        route: 'vitals',
        component: 'vitals'
      },
      {
        id:'reports',
        text: '检查报告',
        icon: 'DocumentCopy',
        route: 'reports',
        component: 'reports'
      }
    ]
  },
  {
    id: 'medical-records',
    text: '病历档案',
    icon: 'Files',
    route: 'medical-records',
    component: 'medical-records'
  },
  {
    id:'first-aid',
    text: '急救指南',
    icon: 'FirstAidKit',
    route: 'first-aid',
    component: 'first-aid'
  },
  {
    id:'find-hospital',
    text: '附近医院',
    icon: 'LocationInformation',
    route: 'find-hospital',
    component: 'find-hospital'
  },
  {
    id: 'system-settings',
    text: '系统设置',
    icon: 'Setting',
    route: 'system-settings',
    component: 'system-settings'
  }
]);

// 监听路由变化，更新侧边栏的激活状态
router.afterEach((to) => {
  sidebarMenuItems.value.forEach(item => {
    // 检查主菜单项是否激活
    const isItemActive = item.route === to.path;
    item.active = isItemActive;

    // 如果有子菜单
    if (item.children) {
      let hasActiveChild = false; // 标记是否有激活的子菜单
      item.children.forEach(child => {
        const isChildActive = child.route === to.path;
        child.active = isChildActive;
        if (isChildActive) {
          hasActiveChild = true;
        }
      });
      // 如果主菜单项本身激活，或者其下有激活的子菜单，则展开该主菜单
      item.expanded = isItemActive || hasActiveChild;
    }
  });
});

// userInfo 现在从 Pinia store 中获取，不再需要在这里定义
const { userInfo } = store

// 可以在这里添加一个 effect 来监听 userInfo 的变化，如果需要的话
// watch(() => store.userInfo, (newVal) => {
//   console.log('User info updated:', newVal);
// }, { deep: true });


const patientInfo = reactive({
  id: 'P20241201001',
  name: '张三',
  age: 45,
  gender: '男',
  vitalSigns: {
    bloodPressure: '120/80 mmHg',
    temperature: '36.5°C',
    pulse: '72次/分',
    weight: '70kg'
  }
})

const diagnosisData = reactive({
  western: {
    complaint: '胸闷气短3天，伴心悸',
    diagnosis: ['冠心病', '心律不齐'],
    symptoms: ['胸闷', '气短', '心悸'],
    testResults: [
      { name: '心电图', result: 'ST段压低', status: 'abnormal' },
      { name: '血脂', result: '正常范围', status: 'normal' },
      { name: '血压', result: '120/80mmHg', status: 'normal' }
    ],
    updateTime: '2024-12-01 14:30'
  },
  traditional: {
    syndrome: '心气虚证',
    constitution: '气虚质',
    inspection: {
      look: '面色少华，唇甲淡白',
      listen: '语声低微',
      ask: '心悸气短，动则加重',
      feel: '脉细弱，舌淡苔白'
    },
    meridian: ['心经', '脾经'],
    updateTime: '2024-12-01 15:00'
  },
  treatment: {
    western: {
      medications: [
        { name: '美托洛尔', dosage: '25mg bid', duration: '1个月' },
        { name: '阿司匹林', dosage: '100mg qd', duration: '长期' }
      ],
      procedures: ['心电图复查', '血脂监测']
    },
    traditional: {
      formula: '补中益气汤加减',
      herbs: [
        { name: '黄芪', dosage: '30g' },
        { name: '党参', dosage: '15g' },
        { name: '当归', dosage: '12g' },
        { name: '白术', dosage: '12g' }
      ],
      acupuncture: ['内关', '神门', '心俞', '脾俞'],
      lifestyle: ['规律作息', '适度运动', '情志调畅']
    }
  },
  records: [
    {
      id: 1,
      date: '2024-12-01T14:30:00',
      type: '门诊',
      doctor: '李医生',
      content: '患者胸闷气短症状好转，继续服药观察',
      category: 'western',
      status: 'completed'
    }
  ]
})

const confirmDialog = reactive({
  visible: false,
  title: '',
  message: '',
  type: 'warning',
  onConfirm: () => {},
  onCancel: () => {}
})

// 事件处理
const handleGoToProfile = () => {
  router.push('/profile')
}

const handleQuickAppointment = () => {
  router.push('/appointments/new')
}

// 导航处理函数
const handleNavigation = (menuItem) => {
  if (menuItem.component) {
    activeComponent.value = componentMap[menuItem.component]
  } else if (menuItem.route) {
    router.push(menuItem.route)
  }
}

const closeSidebar = () => {
  sidebarVisible.value = false
}

const handleTabChange = (tab) => {
  activeTab.value = tab
}

const handleDataUpdate = (type, data) => {
  diagnosisData[type] = { ...diagnosisData[type], ...data }
  ElMessage.success('数据已更新')
}

// Provide 全局数据
provide('confirmDialog', confirmDialog)
provide('patientInfo', patientInfo)

// 生命周期
onMounted(async () => {
  try {
    await store.fetchUserInfo();
    ElMessage.success('数据加载成功');
  } catch (error) {
    ElMessage.error('数据加载失败');
  }
});
</script>

<style scoped>

.health-atlas-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
}

.main-layout {
  display: flex;
  min-height: calc(100vh - 80px);
}

.sidebar-wrapper {
  width: 300px;
  flex-shrink: 0;
}

.content-wrapper {
  flex: 1;
  overflow: hidden;
  position: relative;
  min-height: 500px;
}

.component-enter-active,
.component-leave-active {
  transition: all 0.3s ease;
}

.component-enter-from,
.component-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

@media (max-width: 1024px) {
  .main-layout {
    flex-direction: column;
  }

  .sidebar-wrapper {
    width: 100%;
    height: auto;
  }
}

/* 新增：组件切换动画 */
.component-enter-active,
.component-leave-active {
  transition: all 0.3s ease;  /* 过渡效果 */
}

.component-enter-from,
.component-leave-to {
  opacity: 0;  /* 透明度动画 */
  transform: translateY(20px);  /* 位移动画 */
}

</style>
